package com.weibotwo.web.controller;

import com.mysql.cj.Session;
import com.weibotwo.common.util.PageResult;
import com.weibotwo.pojo.*;
import com.weibotwo.service.UserService;
import com.weibotwo.service.WeiBoService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName MainController
 * @Author 天火
 * @Date 2019-03-04
 * @Version 1.0
 */
@Controller
public class MainController {

    @Autowired
    private WeiBoService weiBoService;

    @Autowired
    private UserService userService;

    private ModelAndView modelAndView = new ModelAndView();

    String sKey;

    @RequestMapping("/home")
    public ModelAndView home_index(@RequestParam(value="pageNum",defaultValue="1") Integer pageNum, HttpSession session){
        modelAndView.clear();
        modelAndView.setViewName("home");
        List<User> users;
        PageResult result;
        User user = (User)session.getAttribute("loginUser");
        if(user==null){
            result = weiBoService.findPageById(pageNum,5);
            users = weiBoService.findTuijianById(2L);
        } else{
            users = weiBoService.findTuijianById(user.getId());
            result = weiBoService.findPageById(pageNum,5,user.getId());

        }
        modelAndView.addObject("weiboList", result.getRows());
        modelAndView.addObject("pageNum",pageNum);
        modelAndView.addObject("pageTotal",result.getPageTotals());
        modelAndView.addObject("tuijian",users);
        return modelAndView;
    }

    /**
     * 用户主页微博查看
     * @param pageNum 页数
     * @param userId 用户ID
     * @return ModelAndView
     */
    @RequestMapping("/userIndex")
    public  ModelAndView userIndex(@RequestParam(value = "pageNum", defaultValue="1") Integer pageNum,String userId){

        modelAndView.clear();
        modelAndView.setViewName("user");
        try{
            Long uId = Long.parseLong(userId);
            User user = userService.findUserByID(uId);
            PageResult result = userService.findWeiboListByUserId(uId,pageNum,5,"all");
            List<User> users = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("user",user);
            modelAndView.addObject("list", result.getRows());	//用户微博信息
            modelAndView.addObject("pageNum",pageNum);
            modelAndView.addObject("pageTotal",result.getPageTotals());
            modelAndView.addObject("tuijian",users);

        }catch (Exception e){
            e.printStackTrace();
        }


        return modelAndView;
    }


    @RequestMapping("/publishWeibo")
    public ModelAndView publishWeibo(String inputbox, @RequestParam("pic") MultipartFile pic, HttpSession session, HttpServletRequest request, HttpServletResponse response){

        Weibo weibo = new Weibo();
        weibo.setmBody(inputbox);
        User user = (User)session.getAttribute("loginUser");
        try{
            response.setContentType("text/html;charset=utf-8;");
            PrintWriter pw = null;
            pw = response.getWriter();
            if(user==null){
                pw.print("请登录");
                modelAndView.setViewName("publish");
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        modelAndView.clear();
        modelAndView.setViewName("redirect:home");
        if(!(pic.isEmpty())){	//如果文件存在，isEmpty文件为空
            //保存文件目录
            String path = request.getSession().getServletContext().getRealPath("/")+"WEB-inf/jsp/upload/pic/"+user.getId()+pic.getOriginalFilename();
            File newFile = new File(path);
            //判断文件目录存在不存在，如果不存在就创建目录
            if(!(newFile.getParentFile().exists())){
                newFile.getParentFile().mkdirs();
            }
            try {
                pic.transferTo(newFile); //转存文件
                weibo.setmImage("upload/pic/"+user.getId()+pic.getOriginalFilename());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            //没有带图片
            weibo.setmImage("null");
        }
        try {
            //保存微博信息
            weibo.setuId(user.getId());
            weiBoService.publishWeibo(weibo);	//保存微博信息
            user.setBlogNumber(user.getBlogNumber()+1);		//将用户的微博数+1
            userService.updateUser(user);		//保存更改后的用户信息
            session.setAttribute("loginUser", user);
            modelAndView.addObject("msg", "发布成功！");
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.addObject("msg", e.getMessage());
        }
        return modelAndView;
    }

    //*********************************Ajax*********************************************//

    /**
     * 点赞功能实现
     * @param session 会话
     * @param weiboId 微博Id
     * @param response 响应
     * @param spanMsg 消息
     * @return  ModelAndView
     */
    @RequestMapping("/weiboLike")
    public ModelAndView weiboLike(HttpSession session, String weiboId, HttpServletResponse response, String spanMsg ,HttpServletRequest request){

        User user = (User)session.getAttribute("loginUser");
        long wId = Long.parseLong(weiboId);
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter pw = response.getWriter();

            //request.setCharacterEncoding("UTF-8");
            spanMsg = request.getParameter("spanMsg");
            spanMsg = URLDecoder.decode(spanMsg, "UTF-8");
            if(user == null){
                pw.print("请登录");
                return null;
            }
            Long likeNum = weiBoService.weiboLike(wId, user.getId());
            if(spanMsg.startsWith("已")){
                pw.println("赞("+likeNum+")"+" &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;");
            }else{
                pw.println("已赞("+likeNum+")" + " &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;");
            }
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 微博转发功能
     * ajax
     */
    @RequestMapping("/weiboTrans")
    public ModelAndView WeiboTrans(HttpSession session,String weiboId,HttpServletResponse resp){
        User user = (User)session.getAttribute("loginUser");
        long wId = Long.parseLong(weiboId);

        resp.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter pw = resp.getWriter();
            if(user == null){
                pw.print("请登录");
                return null;
            }
            Long transNum = weiBoService.weiboTrans(wId, user.getId());
            pw.println("转发("+transNum+")");
            pw.flush();
            pw.close();
            modelAndView.setViewName("forward:home");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微博评论
     * url="pubComment?weiboId="+id+"comment="+msg.value;
     * weiboId : 微博编号
     * comment : 评论内容
     */
    @RequestMapping("pubComment")
    public ModelAndView pubComment(String weiboId,String comment,HttpSession session,HttpServletResponse resp,HttpServletRequest request) throws UnsupportedEncodingException {
        long id = Long.parseLong(weiboId);		//获取微博id
        User loginUser = (User)session.getAttribute("loginUser");	//评论人

        WeiboComm weiboComm = new WeiboComm();
        //组装数据源
         comment = new String(comment.getBytes("ISO-8859-1"), "UTF-8");
        weiboComm.setWeiboId(id);	//微博id
        weiboComm.setCommentId(loginUser.getId()); 	//评论人id
        weiboComm.setCommentBody(comment);
        weiboComm.setCommentState(1); 	//评论状态 1代表正常 2代表被删除 3代表被举报

        try {
            resp.setContentType("text");
            PrintWriter pw = resp.getWriter();
            if(loginUser == null){
                pw.print("请登录");
            }else{
                Long commNum = weiBoService.weiboComment(weiboComm);
                pw.print("评论("+commNum+")");
            }


            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping(value= "/getComm")
    public ModelAndView getComm(String weiboId,String p,String fy,HttpSession session,HttpServletResponse response){
        modelAndView.clear();
        modelAndView.setViewName("comment");
        long wId = Long.parseLong(weiboId);
        int page = Integer.parseInt(p);
        int zt = Integer.parseInt(fy);


        JSONArray json = null;
        PageResult result ;
        try {
            Long cNum = weiBoService.findCommNum(wId);
            WeiiBoPojo weiiBoPojo = weiBoService.findWeiboByWId(wId);


            result = weiBoService.findWeiboComm(wId,page,zt);
            int commTotalPage = result.getPageTotals();
            modelAndView.addObject("cNum",cNum);

            modelAndView.addObject("weibo",weiiBoPojo);
            modelAndView.addObject("commenList",result.getRows());
            modelAndView.addObject("pageTotal",commTotalPage);
            modelAndView.addObject("pageNum",p);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }
    /**
     * 功能:判断用户输入的验证码是否正确，前端采用ajax异步交互，接受发来的请求与session中保存的验证码
     * 做比较，如果正确，返回显示正确的图片，如果错误，返回验证码有误的文字和错误的图片，使用ajax实现异步交
     * 互，局部刷新
     * @param yzm 验证码，在前端js中发来的异步请求所携带用户填写的验证码
     */
    @RequestMapping("AuthCodeServlet")	//局部刷新返回用户输入的验证码是否正确
    public String authCodeServlet(HttpSession session,HttpServletResponse resp,String yzm){
        modelAndView.clear();
        try {
            String ac = (String) session.getAttribute("authCode");
            resp.setContentType("text");
            PrintWriter pw = resp.getWriter();
            if(ac.equals(yzm)){
                //验证码正确
                pw.print("<img src='icon/ok.png' align='absmiddle'> ");
            }else{
                //验证码错误
                pw.print("<img src='icon/err.png' align='absmiddle'> <font color='red'>验证码错误</font>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @deprecated 微博收藏，接受Ajax传值
     * @param weiboId 微博Id
     * @param session
     * @return
     */
    @RequestMapping("/weiboCollect")
    @ResponseBody
    public String collect(String weiboId,HttpSession session,HttpServletResponse response){
        User user = (User)session.getAttribute("loginUser");
        long wId = Long.parseLong(weiboId);

        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter pw = response.getWriter();
            if(user == null){
                pw.print("请登录");
                return null;
            }

            weiBoService.weiboCollect(user,wId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param key
     * @param ac
     * @param pag
     * @param session
     * @return
     */
    @RequestMapping("/search")
    public ModelAndView seach(String key,String ac,int pag,HttpSession session){
        modelAndView.clear();
        List<User> userTuiJian;
        if(key != null){
            sKey = key;
        }
        User user = (User) session.getAttribute("loginUser");
        if("weibo".equals(ac)){
            modelAndView.setViewName("seachWeiboPage");
        }else if("user".equals(ac)){
            modelAndView.setViewName("seachUserPage");
        }
        try {
           PageResult result = weiBoService.seachWeibopojoList(sKey,pag,ac);
            modelAndView.addObject("map", result);
            if(user!=null) {
                userTuiJian = weiBoService.findTuijianById(user.getId());
            }else{
                userTuiJian  = weiBoService.findTuijianById(3L);
            }
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("pageNum",pag);
            modelAndView.addObject("key",sKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("/shell")
    public ModelAndView conchIndex(HttpSession session,String operation,@RequestParam(value = "pageNum", defaultValue = "1") int pageNum){
        modelAndView.clear();
        modelAndView.setViewName("user/shell");
        User user = (User) session.getAttribute("loginUser");
        String conchOperation = "";
        List<User> userTuiJian;
        if(operation != null){
            conchOperation = operation;
        }
        try {
            //查找贝壳显示
            Map<String, Object> map = userService.shellIndex(user,conchOperation,pageNum);
            if(map ==null){
                modelAndView.addObject("msg","请登录");
            }
            if(user!=null){
                userTuiJian= weiBoService.findTuijianById(user.getId());
            }else {
                userTuiJian = weiBoService.findTuijianById(2L);
            }

            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("conch", map);
            modelAndView.addObject("operation",operation);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("/publishShell")
    public ModelAndView publishConch(HttpSession session,String inputbox,int sNumber){
        modelAndView.clear();

        User user = (User) session.getAttribute("loginUser");

        Shell shell = new Shell();
        shell.setShellBody(inputbox);
        shell.setsNumber(sNumber);
        shell.setUserId(user.getId());
        Date date = new Date();
        //shell.jsp.setShellTime(date.toString());

        try {
            userService.publishShell(shell);
            modelAndView.addObject("msg", "发布成功！");
            modelAndView.setViewName("user/shell");
            //海螺分页

            //查找海螺显示
            //调用service
            Map<String, Object> map = userService.shellIndex(user,"NEWs",1);

            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("conch", map);

        } catch (Exception e) {
            modelAndView.setViewName("login");
            modelAndView.addObject("msg", "请登录！");
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 海螺详细问题页面
     * @param session session
     * @param shellId
     * @return
     */
    @RequestMapping("/shellDetail")
    public ModelAndView conchDetail(HttpSession session,long shellId){
        modelAndView.clear();
        modelAndView.setViewName("user/shellDetail");
        User user = (User) session.getAttribute("loginUser");
        List<User> userTuiJian ;

        try {
            Map<String, Object> map = userService.shellDetail(shellId);
            if(user!=null){
                userTuiJian = weiBoService.findTuijianById(user.getId());
            }else {
                userTuiJian = weiBoService.findTuijianById(1L);
            }

            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("detailMap", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 回复贝壳问题
     * @param userId
     * @param shellId
     * @param inputbox
     * @return
     */
    @RequestMapping("shellComm")
    public ModelAndView createCommtoConch(long userId,long shellId,String inputbox,HttpSession session){
        modelAndView.clear();
        modelAndView.setViewName("redirect:shellDetail");
        User user = (User) session.getAttribute("loginUser");
        WeiboComm comm = new WeiboComm();	//使用微博评论实体作为海螺评论实体
        comm.setBeCommentId(userId);
        comm.setCommentId(user.getId());
        comm.setWeiboId(shellId);	//将微博id属性作为海螺id
        comm.setCommentBody(inputbox);
        comm.setCommentState(100);
        Date date = new Date();
        comm.setCommentDate(date);
        try {
            weiBoService.weiboComment(comm);
            modelAndView.addObject("shellId", shellId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 贝壳答案采纳
     * @param shellId
     * @param comm
     * @return
     */
    @RequestMapping("/adoptComm")
    public ModelAndView adoptComm(long shellId,long comm){
        modelAndView.clear();
        modelAndView.setViewName("redirect:shellDetail");
        try {
            userService.adoptComm(shellId,comm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        modelAndView.addObject("shellId", shellId);
        return modelAndView;
    }

    @RequestMapping("/isLogin")
    public String isLoginState(HttpSession session,HttpServletResponse response){
        User user = (User) session.getAttribute("loginUser");
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter pw = response.getWriter();
            if(user == null){
                pw.print("请登录");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }











}
